package com.glodon.paas.job.server.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import com.glodon.paas.job.extend.spring.AutowaireHibernateDAOSupport;
import com.glodon.paas.job.model.Task;
import com.glodon.paas.job.server.dao.TaskDAO;

@Repository
public class TaskDAOImpl extends AutowaireHibernateDAOSupport implements TaskDAO {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void saveOrUpdate(Task task) {
        Task result = get(task.getTaskId());
        if (result != null && result.getValues() != null) {
            Map oldValues = result.getValues();
            Map values = task.getValues();
            Set keySet = oldValues.keySet();
            for (Object key : keySet) {
                if (!values.containsKey(key)) {
                    values.put(key, oldValues.get(key));
                }
            }
        }
        getHibernateTemplate().saveOrUpdate(task);
    }

    @Override
    public void save(Task task) {
        getHibernateTemplate().save(task);
    }

    @Override
    public boolean delete(Task task) {
        return getHibernateTemplate().bulkUpdate("delete from Task task where task.id = ?", task.getTaskId()) > 0;
    }

    @Override
    public Task get(String id) {
        return getHibernateTemplate().get(Task.class, id);
    }

    @Override
    public List<Task> getAll() {
        return getHibernateTemplate().loadAll(Task.class);
    }
}
